﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SiteParser.Console.SitesConfig.SaksSite.Entities;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;
using SiteParser.Core.Logging;

namespace SiteParser.Console.SitesConfig.SaksSite.DataEntities
{
	public class MySqlDataImporter
	{
		private MySqlConnection mySqlConnection;

		public void ImportDataToDB(SaksSiteEntity siteInfo, string dbConnectionString) {
			using (mySqlConnection = new MySqlConnection()) {
				mySqlConnection.ConnectionString = dbConnectionString;
				MageNtoDb magentoDb = new MageNtoDb(mySqlConnection);

				mySqlConnection.Open();

				foreach (var catalogItem in siteInfo.CatalogItems) {
					ProcessCatalogItem(magentoDb, catalogItem);
				}
			}
		}

		private void ProcessCatalogItem(MageNtoDb magentoDb, CatalogItem catalogItem) {
			if (catalogItem != null && !string.IsNullOrEmpty(catalogItem.Name)) {
				CatalogDataProvider dataProvider = new CatalogDataProvider();

				var insertParams = new CatalogItemInsertParameters() {
					AttributeSetId = DBConstants.CATEGPRY_DEFAULT_ATTRIBUTE_SET_ID,
					EntityTypeId = DBConstants.CATEGORY_ENTITY_TYPE_ID,
					Label = catalogItem.Name,
					Level = 2,
					ParentId = DBConstants.ROOT_CATEGORY_ID,
					UrlId = catalogItem.Name.GetHashCode().ToString(),
					ChildrenCount = catalogItem.SubitemsList != null ? catalogItem.SubitemsList.Count : 0
				};

				uint categoryId = dataProvider.InsertCatalogItem(mySqlConnection, magentoDb, insertParams);
				catalogItem.DbEntityId = categoryId;

				foreach (var subitem in catalogItem.SubitemsList) {
					ProcessCatalogSubitem(magentoDb, subitem, categoryId);
				}
			}
		}

		private void ProcessCatalogSubitem(MageNtoDb magentoDb, CatalogSubitem subitem, uint parentElementId)
		{
			if (subitem != null && !string.IsNullOrEmpty(subitem.Name)) {
				CatalogDataProvider catalogProvider = new CatalogDataProvider();

				var insertParams = new CatalogItemInsertParameters() {
					AttributeSetId = DBConstants.CATEGPRY_DEFAULT_ATTRIBUTE_SET_ID,
					EntityTypeId = DBConstants.CATEGORY_ENTITY_TYPE_ID,
					Label = subitem.Name,
					Level = 2,
					ParentId = parentElementId,
					UrlId = subitem.Name.GetHashCode().ToString(),
					ChildrenCount = subitem.GroupedSubitems != null ? subitem.GroupedSubitems.Count : 0
				};

				uint categoryId = catalogProvider.InsertCatalogItem(mySqlConnection, magentoDb, insertParams);

				subitem.DbEntityId = categoryId;

				if (subitem.GroupedSubitems != null && subitem.GroupedSubitems.Count > 0) {
					foreach (var item in subitem.GroupedSubitems) {
						ProcessCatalogSubitem(magentoDb, item, categoryId);
					}
				}

				if (subitem.InventoryList != null && subitem.InventoryList.Count > 0) {
					foreach (var product in subitem.InventoryList) {
						try {
							ProcessProduct(product, categoryId);
						}
						catch (Exception exc) {
							Logger.Error(string.Format("Unable to migrate product '{0}'. {1}",
								product != null && product.BriefDescription != null ? product.BriefDescription.MainImagePath : string.Empty, exc));
								
						}
					}
				}

			}
		}

		private void ProcessProduct(InventoryItem product, uint categoryId) {
			ProductDataProvider productProvider = new ProductDataProvider();

			var insertParams = new ProductInsertParameters() {
				BaseImage = product.FullDescription != null ? NormalizeString(product.FullDescription.MainImagePath) : string.Empty,
				SmallImage = NormalizeString(product.BriefDescription.MainImagePath),
				Thumbnail = NormalizeString(product.BriefDescription.MainImagePath),
				Images = new string[] { NormalizeString(product.BriefDescription.MainImagePath), NormalizeString(product.BriefDescription.SecondaryImagePath) },
				Name = NormalizeString(product.BriefDescription.Manufacter),
				Price = NormalizePrice(product.BriefDescription.Price),
				Quantity = byte.MaxValue,
				Categories = new uint[] { categoryId },
				ShortDescription = NormalizeString(GetProductDescription(product)),
				Description = NormalizeString(GetProductFullDescription(product))
			};

			productProvider.InsertProduct(mySqlConnection, insertParams);
		}

		private string GetProductDescription(InventoryItem product) {
			if (product.BriefDescription != null) {
				return string.Format("{0}\n{1}", product.BriefDescription.Manufacter, product.BriefDescription.TradeMark);
			}
			else {
				return string.Empty;
			}
		}

		private string GetProductFullDescription(InventoryItem product) {
			return product.FullDescription != null ? product.FullDescription.Description : string.Empty;
		}

		private int NormalizePrice(string price) {
			int result;
			return int.TryParse(Regex.Match(price, @"\d+").Value, out result) ? result : 0;
		}

		private string NormalizeString(string description) {
			return !string.IsNullOrEmpty(description) ? Regex.Replace(description,"'|\"", @"\'") : string.Empty;
		}

	}
}
